import React, {useState} from 'react';
import {Layout, Card, List, Input, Drawer, Radio, Table, Button} from 'antd';
import {PageContainer} from '@ant-design/pro-components';
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import { coy } from 'react-syntax-highlighter/dist/esm/styles/prism';
import {
  getAllDatabasesUsingPost,
  getAllTablesUsingPost,
  getCreateTableSqlUsingPost, getTableDataUsingPost, getTableStructUsingPost
} from '@/services/easyapi/eDatasource';

const {Sider, Content} = Layout;
const structureColumns = [
  {
    title: 'Column Name',
    dataIndex: 'columnName',
    key: 'columnName',
  },
  {
    title: 'Data Type',
    dataIndex: 'dataType',
    key: 'dataType',
  },
  {
    title: 'Default Value',
    dataIndex: 'columnDefault',
    key: 'columnDefault',
  },
  {
    title: 'Nullable',
    dataIndex: 'isNullable',
    key: 'isNullable',
    render: (isNullable: string) => (isNullable === 'YES' ? 'Yes' : 'No'),
  },
  {
    title: 'Primary Key',
    dataIndex: 'isPrimaryKey',
    key: 'isPrimaryKey',
    render: (isPrimaryKey: number) => (isPrimaryKey ? 'Yes' : 'No'),
  },
  {
    title: 'Extra',
    dataIndex: 'extra',
    key: 'extra',
  },
];
const DatasourceDetailTableList: React.FC = () => {
  const [selectedItem, setSelectedItem] = useState<string | null>(null);
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const [databaseList, setDatabaseList] = useState<string[]>([]);
  const [searchValue, setSearchValue] = useState<string>('');
  const [tableList, setTableList] = useState<string[]>([]);
  const [datasourceId, setDataSourceId] = useState<number>(0)
  const [databasesName, setDatabasesName] = useState<string>('')
  const [tableName, setTableName] = useState<string>('')
  const [selectedOption, setSelectedOption] = useState<string>('preview');
  const [columns, setColumns] = useState<any[]>([]); // To store the table columns
  const [data, setData] = useState<any[]>([]); //
  const [structureData, setStructureData] = useState<any[]>([]); // To store the structure data
  const [createTableSql, setCreateTableSql] = useState<string>('')
  const fetchCreateTableSql = async () => {
    const res = await getCreateTableSqlUsingPost({
      id: datasourceId,
      databaseName: databasesName,
      tableName: tableName
    });
    if (res.code === 200) {
      setCreateTableSql(res.data); // Store the fetched SQL in the state
    }
  }

  const fetchTableData = async () => {
    try {
      const res = await getTableDataUsingPost({
        id: datasourceId,
        databaseName: databasesName,
        tableName: tableName,
      });

      if (res.code === 200) {
        const allData = res.data || [];
        if (allData.length > 0) {
          // 第一行数据作为列名
          const columnsData = allData[0].map((col: string) => ({
            title: col, // 列标题
            dataIndex: col, // 数据索引
            key: col, // 每列的唯一键
          }));

          // 剩余的行数据
          const tableData = allData.slice(1).map((row: string[]) => {
            // 将行数据转换为对象形式，键为列名
            const rowObject: { [key: string]: any } = {};
            columnsData.forEach((col: any, index: number) => {
              rowObject[col.dataIndex] = row[index];
            });
            return rowObject;
          });

          setColumns(columnsData);
          setData(tableData);
        }
      } else {
        console.error('获取表格数据失败');
      }
    } catch (error) {
      console.error('获取表格数据时出错:', error);
    }
  }

  const fetchStructureData = async () => {
  const res =   await  getTableStructUsingPost({
      id:datasourceId,
      databaseName: databasesName,
      tableName: tableName
    })
    if (res.code === 200) {
      setStructureData(res.data || []);
    }
  }
  const handleOptionChange = (e: any) => {
    setSelectedOption(e.target.value);
    if (e.target.value==='createTable') {
      fetchCreateTableSql()
    }
    if (e.target.value==='preview') {
      fetchTableData()
    }

    if (e.target.value==='structure') {
      fetchStructureData();
    }
  };
  // Fetch the database list
  const fetchDatabaseList = async (id: number) => {
    const res = await getAllDatabasesUsingPost({
      id: id,
    });
    if (res.code === 200) {
      setDatabaseList(res.data || []);
    } else {
      setDatabaseList([]);
    }
  };
  const fetchTableList = async (id: number, databaseName: string) => {
    const res = await getAllTablesUsingPost({
      id: id,
      databaseName: databaseName
    })
    if (res.code === 200) {
      setTableList(res.data || []);
    } else {
      setDatabaseList([]);
    }
  }

  // Load data on initial render
  React.useEffect(() => {
    let id = localStorage.getItem('dataSourceId');
    console.log(id);
    if (id === '') {
      id = '1';
    }
    setDataSourceId(Number(id));
    fetchDatabaseList(Number(id));
  }, []);

  return (
    <Layout style={{height: '100vh', backgroundColor: 'rgb(0,0,0)'}}>
      <Sider
        width={350}
        style={{
          backgroundColor: '#000000',
          borderRight: '1px solid #f0f0f0',
          padding: '24px',
          overflow: 'auto', // Add overflow here to enable scrolling
          height: '100vh' // Ensures the Sider takes up the full viewport height
        }}
      >
        <PageContainer>
          {/* Search bar */}
          <Input.Search
            placeholder="搜索项目"
            value={searchValue}
            onChange={(e) => setSearchValue(e.target.value)}
            style={{marginBottom: '16px'}}
          />

          {/* Project list */}
          <List
            dataSource={databaseList.filter((item) =>
              item.toLowerCase().includes(searchValue.toLowerCase())
            )}
            renderItem={(item) => (
              <List.Item
                key={item}
                onClick={() => {
                  setDatabasesName(item)
                  fetchTableList(datasourceId, item);
                }}
                style={{cursor: 'pointer'}}
              >
                <List.Item.Meta title={item}/>
              </List.Item>
            )}
          />
        </PageContainer>
      </Sider>

      <Layout style={{padding: '2px', backgroundColor: '#000000'}}>
        <Layout.Content
          style={{
            backgroundColor: '#000000',
            border: '1px solid #f0f0f0',
            borderRadius: '8px',
            padding: '24px',
            overflowY: 'auto', // 添加滚动条
            maxHeight: '100%', // 设置最大高度，根据需要调整
          }}
        ><h2 style={{marginBottom: '16px'}}>{databasesName}数据表</h2>
          {/* Project list */}
          <List
            dataSource={tableList.filter((item) =>
              item.toLowerCase().includes(searchValue.toLowerCase())
            )}
            renderItem={(item) => (
              <List.Item
                key={item}
                style={{cursor: 'pointer'}}
                onClick={() => {
                  setTableName(item)
                  setShowDetail(true);
                }}
              >
                <List.Item.Meta title={item}/>
              </List.Item>
            )}
          />
        </Layout.Content>
      </Layout>

      <Drawer
        width={"70%"}
        open={showDetail}
        onClose={() => {
          setSelectedItem(null);
          setShowDetail(false);
        }}
        closable={false}
      >
        <Radio.Group
          value={selectedOption}
          onChange={handleOptionChange}
          style={{marginBottom: '16px'}}
        >
          <Radio.Button value="preview">数据预览</Radio.Button>
          <Radio.Button value="createTable">创建表语句</Radio.Button>
          <Radio.Button value="structure">表结构</Radio.Button>
        </Radio.Group>

        {/* Conditionally render content based on selected option */}
        {selectedOption === 'preview' ? (
          // Data Preview Table
          <Table
            columns={columns}
            dataSource={data}
            pagination={false}
            bordered={true}
            rowKey={(record) => record.id || Math.random().toString()}
            components={{
              body: {
                cell: (props: any) => (
                  <td {...props} style={{ border: '1px solid #d9d9d9' }} />
                ),
              },
            }}
            style={{ maxHeight: '500px', overflowY: 'auto' , borderCollapse: 'collapse'}} // Assuming each record has an `id`
          />
        ) : selectedOption === 'createTable' ? (
          // Create Table Statement
          <div style={{padding: '10px', backgroundColor: '#000000', borderRadius: '5px', minHeight:'40%', maxHeight:'80%'}} >
            <SyntaxHighlighter  language="sql" style={coy} customStyle={{
              backgroundColor: '#ffffff', // Black background
              color: '#ffffff',           // White text color for better contrast
              padding: '10px',
              borderRadius: '4px',
            }}>
              {createTableSql || 'Loading...'}
            </SyntaxHighlighter>
          </div>
        ) : (
          // Table Structure
          <Table
            columns={structureColumns}
            dataSource={structureData}
            pagination={false}
            bordered={true}
            components={{
              body: {
                cell: (props: any) => (
                  <td {...props} style={{ border: '1px solid #d9d9d9' }} />
                ),
              },
            }}
            style={{ maxHeight: '500px', overflowY: 'auto' , borderCollapse: 'collapse'}}
            rowKey={(record) => record.id} // Assuming each structure item has an `id`
          />
        )}

        {/* Footer: Refresh and Load Data */}
        <div style={{marginTop: '16px', textAlign: 'right'}}>
          <Button
            type="primary"
            onClick={() => {
              if (selectedOption === 'preview') {
                // Refresh data preview
                fetchTableData()
              } else if (selectedOption === 'structure') {
                // Refresh table structure
                fetchStructureData()
              }
            }}
          >
            刷新数据
          </Button>
        </div>
      </Drawer>
    </Layout>
  );
};

export default DatasourceDetailTableList;
